//
//  SearchViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/20.
//

import UIKit
import CoreBluetooth

class SearchViewController: EPViewController {
    @IBOutlet var tips1: UILabel!
    @IBOutlet var tips2: UILabel!
    var array = [CBPeripheral]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    override func initUI() {
        self.title = LS("搜索设备")
        self.view.backgroundColor = .white
        
        weak var weakself = self
        self.tableViewStyle = .plain
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        let header = self.tableView.mj_header as! MJRefreshNormalHeader
        header.setTitle(LS("搜索设备..."), for: .refreshing)
        self.tableView.refreshBlock = { boo in
            weakself?.search()
        }
        self.tableView.mj_header?.beginRefreshing()
        self.tableView.register(DeviceCell.nib(), forCellReuseIdentifier: DeviceCell.ID())
        self.tableView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview().inset(0)
        }
    }
    
    func search(){
        self.array.removeAll()
        scan {[weak self] in
            self?.array = BLE.searchedPeripherals
            self?.tableView.reloadData()
        }
        self.perform(#selector(stopSearch), with:nil, afterDelay:10)
    }
    
    @objc func stopSearch(){
        self.tableView.mj_header?.endRefreshing()
        self.tips1.isHidden = self.array.count > 0
        self.tips2.isHidden = self.array.count > 0
    }
    
}

//MARK: - UITableViewDataSource
extension SearchViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DeviceCell.ID()) as! DeviceCell
        let peripheral = self.array[indexPath.row]
        cell.title.text = peripheral.name
        cell.statues.text = peripheral.state == .connected ? LS("已连接") : LS("未连接")
        cell.statues.textHexColor = peripheral.state == .connected ? "#00C2B7" : "#FF485C"
        return cell
    }
    
    
}
//MARK: - UITableViewDelegate
extension SearchViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let peripheral = self.array[indexPath.row]
        if BLE.connectedPeripherals.count > 0 && BLE.connectedPeripherals.first?.mac ?? "" == peripheral.mac{
            DispatchQueue.main.async {
                self.alert(LS("提示"), LS("您链接当前设备")) {} _: {}
            }
            return
        }
        if BLE.connectedPeripherals.count >= 1 {
//            DispatchQueue.main.async {
//                self.alert(LS("提示"), LS("您已连接1个设备，前连接吗？")) {} _: {}
//            }
//            return
        }
        
        
        if peripheral.state != .connected && peripheral.state != .connecting{
            BLE.connect(self.array[indexPath.row]){status in
                self.tableView.reloadData()
                switch status {
                case .connectedSucces:
                    RLHud.start(LS("连接成功"), stopTime: 1, handle: {
                        self.navigationController?.popToRootViewController(animated: true)
                    })
                default:
                    return
                }
            }
            RLHud.start(LS("连接中"), stopTime: 1) {}
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

